package net.qiqb.core.domain;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import lombok.extern.slf4j.Slf4j;
import net.qiqb.core.domain.annotation.EntityIdGenerator;

import java.lang.reflect.Constructor;

/**
 * 雪花id生成器。
 */
@Slf4j
public class SnowflakeIdGenerator<T> implements EntityIdGenerator<T> {

    private final Class<T> idClazz;

    public SnowflakeIdGenerator(Class<T> idClazz) {
        this.idClazz = idClazz;
    }


    @Override
    public T generate() {
        final long idVal = IdUtil.getSnowflake().nextId();
        if (idClazz.equals(Long.class)) {
            final T longId = (T) Long.valueOf(idVal);
            return longId;
        }
        if (idClazz.equals(String.class)) {
            return (T) String.valueOf(idVal);
        }
        Constructor<T> constructor = ReflectUtil.getConstructor(idClazz, Long.class);
        if (constructor != null) {
            return ReflectUtil.newInstance(idClazz, idVal);
        }
        constructor = ReflectUtil.getConstructor(idClazz, String.class);
        if (constructor != null) {
            return ReflectUtil.newInstance(idClazz, String.valueOf(idVal));
        }
        log.error("");
        throw new IllegalStateException("实体类：" + idClazz.getName() + "需要一个 Long 或者String 参数的构造器");
    }

}
